# 导入异步任务队列库  celery

from celery import Celery

import asyncio

# 建立实例

app = Celery('tornado')

# 设置代理/队列   redis 消息队列  rabbitmq  kafka   rocketmq

app.conf.broker_url = 'redis://localhost:6379'

# 设置任务结果
app.conf.result_backend = 'redis://localhost:6379'

# 设置时区
app.conf.timezone = 'Asia/Shanghai'

from test_queue import MysqlDb
from db import User

import time

# 导入定时任务列表
app.conf['imports'] = ['delay_task']

# 导入延时时间戳
from datetime import timedelta

# 配置定时任务
app.conf.beat_schedule = {
    # 声明任务/任务可能有多个
    'task1': {
        'task': 'delay_task.async_consume',
        # 设置时间
        'schedule': timedelta(seconds=10),
        # 参数
        'args': ()
    }
}


# 设置消费任务

async def consume(uid):
    mydb = MysqlDb()

    sql = "select * from `user` where type = 2"
    res = mydb.read_list(sql)
    dicts = {}
    for index, val in enumerate(res):
        dicts[index + 1] = val['id']

    num = hash(int(time.time()) % len(dicts) + 1)

    print(num, dicts, dicts[num])

    mydb.update("update `user` set auid = %s where id = %s" % (dicts[num], uid))

    return '消费任务'


# 装饰器调用异步任务     任务等级   0-9优先级  越来越低
@app.task(name='tornado', property=2)
def async_consume(uid):
    # 调用异步任务
    return asyncio.run(consume(uid))
